<template>
<div>
  <div style="width: 70%;height: 500px;margin: 0 auto">
    <el-container>
      <el-header style="color: white">
        <p>欢迎来到随聊</p>
        <el-button type="success" round style="position: fixed;left: 70%;top: 12%" @click="loginout">退出登录</el-button>
      </el-header>
      <div  style="height: 40px;width: 100%;background-color: #1794c9">
        <p style="margin-right: 85%;color: white">在线聊友</p>
      </div>
      <el-container>
        <el-aside width="200px">

          <div  style="width: 180px;height: 500px;margin: 20px auto">
            <el-row>
              <el-card style="height: 70px" shadow="hover" v-for="(user,index) in Users" :key="index">

                <el-button  v-if="selectId==user.id" type="primary"
                 style="width: 100%" @click="select(user.id,user.username)"

                >
                  <p v-if="user.id!=currentId">
                      <i>{{user.username}}</i>
                  </p>
                  <p v-else>ME</p>


                </el-button>

                <el-button v-else type="primary" plain
                           style="width: 100%" @click="select(user.id,user.username)"

                >

                    <p v-if="user.id!=currentId">

                      <el-badge v-if="badgeMes(user.id)" value="new" class="item">
                        <i>{{user.username}}
                        </i>
                      </el-badge>
                      <el-badge v-else>
                        <i>{{user.username}}</i>
                      </el-badge>
                    </p>
                    <p v-else>ME</p>



                </el-button>

              </el-card>
            </el-row>
          </div>

        </el-aside>

        <el-main>

          <el-main class="show" style="width: 90%;margin: 0 auto;height: 350px;
          background-color: #f0faff;border: 5px #2981ce;border-radius: 10px;

          ">
          <div >
<!--            这部分是咱们的对话内容-->
            <div style="width: 90%;height: 80px;margin: 0 auto"
                 v-for="(Message,index) in MessagesList" :key="index"
            >
              <div v-model="currentId" v-if="currentId!==Message.fromID && selectId==Message.fromID">
                <br>
                <div  style="display:inline-block;width: 10%;
                border: 1px solid #14e0bf;;font-size: 3px;border-radius: 100px"
                >

                  <p style="text-align: center;">{{Message.fromName}}:</p>
                </div>
                <div style="display:inline-block;width: 60%;
               border-radius: 10px;border: 1px solid #0c93ef;"
                >
                  <p style="width: 100%;text-align: left">{{Message.message.message}}</p>
                </div>

              </div>


              <div v-model="currentId" v-if="currentId===Message.fromID  && selectId==Message.message.toID"
              >

                <div style="display:inline-block;width: 60%;
                border-radius: 10px;border: 1px solid #0c93ef;"
                >
                  <p style="width: 100%;text-align: right">{{Message.message.message}}</p>
                </div>

                <div  style="display:inline-block;width: 10%;
                border: 1px solid #14e0bf;;font-size: 3px;border-radius: 100px"
                >
                  <p style="text-align: center;">:{{currentName}}</p>
                </div>
              </div>

            </div>
          </div>


          </el-main>
          <br>
          <div style="width: 90%;margin: 0 auto;
          background-color: white;border-radius: 5px;
          ">
            <el-input v-model="sendMsg" type="textarea" :rows="3"
                      placeholder="说点什么吧~"

            ></el-input>
            <br><br>
            <el-button style="width: 15%;margin-left: 85%" @click="submit" type="primary">
              发送
            </el-button>
          </div>


        </el-main>
      </el-container>
    </el-container>
  </div>
  <router-view/>
</div>
</template>

<script>

export default {
  name: "main",
  data() {

    return {
        read: new Set(),
        lastselectId: -2,
        selectId: -1,
        currentId: null,
        currentName: null,
        sendMsg: null,
        sending: null,
        MessagesList: [
        ],
        Users:[
          {"id":1,"username":"小米"},
          {"id":2,"username":"小明"},
          {"id":3,"username":"小铭"},
          {"id":4,"username":"小敏"},

        ]
    }
  },
  beforeRouteEnter: (to, from, next) => {
    console.log("准备进入主页");
    let islogin = localStorage.getExpire("token")
    if(!islogin){
      next({path:'/login'});
    }
    next();
  },
  methods:{
    freshMyMessage(sendMsg){
    //  这个主要是自己发送的消息不会再被服务器转发给自己，需要本地刷新一下
      let MyMessage={
        "isSystem": false,
        "fromID": this.currentId,
        "fromName": this.currentName,
        "message":sendMsg
      }
      this.MessagesList.push(MyMessage)
    },
    badgeMes(ID){
      return this.read.has(Number(ID));
    },
    loadMessage(selectID,userName){
      this.axios({
        url: "/boot/loadmessage",
        method: 'post',
        data: {
          currentId:  this.currentId,
          currentName: this.currentName,
          selectID: selectID,
          userName: userName
        }
      }).then(res =>{
        let data = res.data
        this.MessagesList = data
      })

    },

    select(selectID,userName){
      this.selectId = selectID

      this.read.delete(Number(selectID))


      //此时选的是别人，需要调用后端数据库获取以前的聊天记录，并且覆盖掉当前的记录
      //为了防止用户恶意点击还需要记录一下是不是点击的同一个人
      if(this.selectId==this.currentId) {

        this.MessagesList=[]

      }
      if(this.lastselectId!=this.selectId && this.selectId!=this.currentId){
        //执行消息覆盖
        //这一部分其实是要访问数据库，来寻找聊天消息的，这里我不想把数据存在本地
        //一方面是因为用户端负载，另一方面，换了浏览器就没了，还是要存在数据库里面

        this.loadMessage(selectID,userName)
        this.lastselectId = this.selectId
      }else {
        if(this.lastselectId==this.selectId){
          alert("正在和当前用户聊天")
        }

      }
    },
    submit(){
      if(this.selectId==-1){
        alert("请选择聊天对象")
        return;
      }
      if(this.sendMsg===null || this.sendMsg.length<1){
        alert("请输入您的消息")
        return
      }if(this.currentId==this.selectId){
        alert("不能和自己聊天哟~")
        return;
      //  选的是自己没用
      }
      this.sendMessage()
      this.sendMsg=null
      console.log("已发送信息")
    },

    loginout(){
      localStorage.removeItem("token");
      this.$router.push('/login')
    }
    ,
    getUserInfo(){
      this.axios({
        url: "/boot/main",
        method: 'get',
        headers: { "token": localStorage.getExpire("token") },

      }).then(res =>{
        let data = res.data
        if(data.success == '0'){
          alert("数据获取异常，请重新登录！")
          this.loginout()
          return;
        }
        if(data.success=='2'){
          alert("登录过期请重新登录")
          this.loginout()
        }
        this.currentId = data.currentId
        this.currentName  = data.currentName
      })

    },
  //  这个是咱们websocket的方法
    //建立连接，初始化weosocket
    sendMessage() {

      let toName = null
      for(var i=0;i<this.Users.length;i++){
        if(this.Users[i].id==this.selectId){
          toName = this.Users[i].username
          break
        }
      }
      this.sending={
        "toID":this.selectId,
        "toName":toName,
        "message":this.sendMsg
      }
      this.freshMyMessage(this.sending)
      this.socket.send(JSON.stringify(this.sending));
    },
    //初始化建立前后台链接
    init() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket("ws://localhost:8000/chat");
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
        this.socket.onclose = this.close;
      }
    },
    //链接成功时的回调函数
    open() {
      console.log("socket连接成功");
    },
    //链接错误时的回调
    error(err) {
      console.log("连接错误" + err);
    },
    //后台消息推送过来，接收的函数，参数为后台推过来的数据。
    getMessage(msg) {
      let dataJson = JSON.parse(msg.data)

      //我们的消息是分为两大类的，一个是系统消息，还有一个是用户消息
      if(dataJson.system){
        this.Users = dataJson.message
      }else {
        console.log(dataJson)
        this.MessagesList.push(dataJson)
        this.read.add(dataJson.fromID)
      }
    },
    //链接关闭的回调
    close(event) {
      //socket是链接的实例，close就是关闭链接
      this.socket.close()
      console.log("断开链接成功");
    },
  },


  mounted() {
    this.getUserInfo()
    this.init()

  }
}
</script>

<style scoped>
.el-header, .el-footer {
  background-color: #1794c9;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.show:hover{
  box-shadow: 0px 15px 30px rgb(30, 136, 225);
  margin-top: 20px;

}

</style>
